import { TranslateService } from '@ngx-translate/core';
import { Injectable } from '@angular/core';
import { Bully, BullySubjectService } from 'app/shared/service';
import { MESSAGE_CHANNEL, SYSTEM_EVENT } from 'app/app.constants';
import * as moment from 'moment';
import { en_US, zh_CN, vi_VN, NzI18nService } from 'ng-zorro-antd';
import { PublicService } from 'app/public/public.service';

export interface UserZone {
    id?: number;
    isTemp?: boolean;
}

@Injectable({
    providedIn: 'root'
})
export class SystemService {
    // 时间和语言
    lang = '';
    time = '';
    langs = [
        // { label: '简体中文', value: 'zh', antdValue: zh_CN },
        { label: 'EN', value: 'en', antdValue: en_US },
        { label: 'Việt nam', value: 'vi', antdValue: vi_VN }
    ];
    langLabel = 'EN';
    timeSetTimer: any;
    userZoneList: UserZone[] = [];
    showPage = false;

    constructor(
        private translate: TranslateService,
        private bully: BullySubjectService,
        private i18n: NzI18nService,
        private pub: PublicService
    ) {}

    langSet() {
        // 语言服务
        const lang = localStorage.getItem('itmp_lang');
        if (!lang) {
            localStorage.setItem('itmp_lang', 'en');
        }
        // 1.默认采用 '英语'
        this.lang = lang ? lang : 'en';

        // 2. 默认采用 '浏览器设置的第一语言'
        /* if (lang) {
            this.lang = lang;
        } else {
            const browserLang = this.translate.getBrowserLang();
            const initLang = browserLang.match(/en|zh|vi/) ? browserLang : 'en';
            this.lang = initLang;
        } */
        this.translate.use(this.lang);
        this.langLabel = this.langs.find(l => l.value === this.lang).label;
    }

    changeLang(lang: string) {
        if (lang) {
            localStorage.setItem('itmp_lang', lang);
            this.lang = lang;
            this.langLabel = this.langs.find(l => l.value === lang).label;
            this.translate.use(lang);
            const antdL: any = this.langs.find(l => l.value === this.lang).antdValue;
            this.i18n.setLocale(antdL);
            const bully: Bully = {
                type: SYSTEM_EVENT.LANG_CHANGE,
                data: lang
            };
            // 广播语言切换事件
            const channel = MESSAGE_CHANNEL.LANGUAGE_CHANNEL;
            this.bully.registerBroadcastSend(channel, bully);
        }
    }

    updateTime() {
        // 设置moment 语言
        const lang = this.lang === 'zh' ? this.lang + '-cn' : this.lang;
        moment.locale(lang);
        this.time = moment().format('LLLL');
    }

    timeSet() {
        this.updateTime();
        if (!this.timeSetTimer) {
            this.timeSetTimer = setInterval(() => this.updateTime(), 1000);
        }
    }

    // 检查业务窗口代开状态, 确保每个业务窗口只能打开一个
    checkChannels(channel: MESSAGE_CHANNEL): boolean {
        const channels = this._getChannelsFromStorage();

        // 先往数组里push,之后再判断是否要关闭这个频道
        channels.push(channel);

        localStorage.setItem('itmp_channels', JSON.stringify(channels)); // 重置storage
        // 检查这个channels的长度
        if (channels.filter(item => item === channel).length > 1) {
            return false;
        }

        // 通过检查可以打开channel
        return true;
    }

    // 每个业务窗口关闭后改变itmp_channels的状态
    updateChannels(channel): void {
        const channels = this._getChannelsFromStorage();

        const index = channels.findIndex(item => item === channel);

        if (index !== -1) {
            channels.splice(index, 1);
            localStorage.setItem('itmp_channels', JSON.stringify(channels));
        }
    }

    private _getChannelsFromStorage(): Array<string> {
        let channels;
        try {
            channels = JSON.parse(localStorage.getItem('itmp_channels'));
        } catch {
            channels = [];
        }
        return channels || [];
    }

    getTableHeaderFilterOptions() {
        if (!this.pub.optionsList.length) {
            this.pub.getSelectOptionsListFromBackend().subscribe(res => {
                if (res.code === '000000') {
                    this.pub.optionsList = res.data;
                    this.showPage = true;
                }
            });
        }
    }
}
